<?php
/**
 * Created by PhpStorm.
 * User: liu85
 * Date: 2019/2/25
 * Time: 21:01
 */

namespace app\admin\controller;


use app\common\consts\AdminConst;
use app\common\consts\BaseConst;
use app\common\helper\AdminInfoHelper;
use app\common\helper\UserHelper;
use app\common\service\AdminService;
use app\common\utils\MyCrypt;
use think\App;
use think\Db;
use think\facade\Log;

class Channel extends Auth
{
    private $channelModel;

    public function __construct(AdminInfoHelper $adminInfoHelper, App $app = null)
    {
        parent::__construct($adminInfoHelper, $app);
        $this->channelModel = new \app\common\model\Channel();
    }

    /**
     * 获取列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        $name = $this->request->get('name', '');
        $map = [];
        if ($name) {
            $map[] = ['name', 'like', '%' . $name . '%'];
        }
        $list = $this->channelModel->where($map)->order('created desc,id desc')->paginate(BaseConst::Admin_DEFAULT_PAGE_SIZE);
        $page = $list->render();
        foreach ($list as $k=>$v){
            $list[$k]['register_url'] = BaseConst::BASE_DOMAIN.'/h5/login?code='.$v['code'];
        }
        $count = $this->channelModel->where($map)->count();
        $this->assign('name', $name);
        $this->assign('list', $list);
        $this->assign('count', $count);
        $this->assign('page',$page);
        return $this->fetch('channel_list');
    }

    /**
     * 添加
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function doAdd()
    {
        $name = $this->request->param('name', '');
        $username = $this->request->param('username', '');
        $password = $this->request->param('password', '');
        $mobile = $this->request->param('mobile', '');
        $reduce = $this->request->param('reduce', 0);
        if ($name == '') {
            _failure('渠道名称不得为空');
        }
        $data['name'] = $name;
        $data['code'] = MyCrypt::makeCode(32);
        $data['reduce'] = $reduce;
        // 启动事务
        Db::startTrans();
        try {
            $this->channelModel->save($data);
            $channelId = $this->channelModel->id;
            if(!empty($username) && !empty($password)){
                AdminService::addAdmin($username, $password, $mobile, AdminConst::TYPE_CHANNEL,$name, $channelId);
            }
            // 提交事务
            Db::commit();
            _success('添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::error($e->getMessage());
            _failure('操作失败');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $id = $this->request->param('id', 0);
        if (!$id) {
            _failure('渠道不存在');
        }
        $channel = $this->channelModel->get($id);
        if (!$channel) {
            _failure('渠道不存在');
        }
        $admin = AdminService::getAdminByChannelId($id);
        $this->assign('admin', $admin);
        $this->assign('info', $channel);
        return $this->fetch();
    }

    /**
     * 编辑
     */
    public function doEdit()
    {
        $id = $this->request->param('id', 0);
        $name = $this->request->param('name', '');
        $username = $this->request->param('username', '');
        $password = $this->request->param('password', '');
        $mobile = $this->request->param('mobile', '');
        $reduce = $this->request->param('reduce', 0);
        if ($name == '') {
            _failure('渠道名称不得为空');
        }
        $channel = $this->channelModel->get($id);
        if (!$channel) {
            _failure('渠道不存在');
        }
        $admin = AdminService::getAdminByChannelId($id);
        if(!$admin){
            $last1 = AdminService::addAdmin($username, $password, $mobile, AdminConst::TYPE_CHANNEL, $name, $id);
        }else{
            $data = [
                'username' => $username,
                'mobile' => $mobile,
                'channel_id' => $id,
                'reduce' => $reduce,
            ];
            if($password){
                $data['pass'] = UserHelper::makePassword($password);
            }
            $last1 = $admin->save($data);
        }
        $last = $channel->save(['name' => $name,'reduce'=>$reduce]);
        self::doLast($last && $last1);
    }

    /**
     * 删除
     */
    public function del()
    {
        $id = $this->request->param('id', 0);
        if (!$id) {
            _failure('渠道不存在');
        }
        $channel = $this->channelModel->get($id);
        $last = $channel->delete($id);
        self::doLast($last);
    }
}